package com.qlc_demo_api.shiro;

import com.qlc_demo_api.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomReal extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Autowired
//    private UserTsService userTsService;

    /**
     * 必须重写此方法，不然会报错
     * @param etoken
     * @return
     */

    @Override
    public boolean supports(AuthenticationToken etoken) {

        return etoken instanceof JWTToken;
    }

    /**
     * 验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("------身份认证方法------");
        String etoken = (String) authenticationToken.getCredentials();
        // 对etoken进行解密
//        String username = JWTUtil.getUsername(etoken);
//        if (username == null || !JWTUtil.verify(etoken, username)) {
//            throw new AuthenticationException("token认证失败！");
//        }
         String username = null;
         try {
             username = JWTUtil.getUsername(etoken);
         }catch (AuthenticationException e) {
             throw new AuthenticationException("etoken非法，不是规范的token，可能被篡改了，或者过期了");
         }

        /*
         * 以下数据库查询可根据实际情况，可以不必再次查询，这里我两次查询会很耗资源
         * 我这里增加两次查询是因为考虑到数据库管理员可能自行更改数据库中的用户信
         */

//        String password = userTsService.getPassword(username);
//        if (password == null) {
//            throw new AuthenticationException("该用户不存在！");
//        }
//        int ban = userTsService.checkUserBanStatus(username);
//        if (ban == 1) {
//            throw new AuthenticationException("该用户已被封号！");
//        }

        if (!JWTUtil.verify(etoken, username) || username == null) {
            throw new AuthenticationException("etoken认证失效，etoken错误或者过期，重新登陆");
        }

        return new SimpleAuthenticationInfo(etoken, etoken, getName());
//        return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), null, getName());
    }

    /**
     *  权限 只有需要检测用户权限的时候才调用此方法，例如：checkRole, checkPermission之类 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("-----权限认证-----授权------");
        String username = JWTUtil.getUsername(principals.toString());
        if (StringUtils.isEmpty(username)) {
            throw new AuthenticationException("etoken认证失败");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;

//        // 获得该用户角色
//        String role = userTsService.getRole(username);
//
//        // 每个用户拥有的默认得权限
//        String rolePermission = userTsService.getRolePermission(username);
//
//        // 每个用户可以设置新的权限
//        String permission = userTsService.getPermission(username);

        //需要将 role, permission 封装到 Set 作为 info.setRoles(), info.setStringPermissions() 的参数
//        Set<String> roleSet = new HashSet<>();
//        Set<String> permissionSet = new HashSet<>();

//        roleSet.add(role);
//        permissionSet.add(rolePermission);
//        permissionSet.add(permission);

        // 设置该用户拥有的角色和权限
//        info.setRoles(roleSet);
//        info.setStringPermissions(permissionSet);
//        return info;
    }
}
